#!/usr/bin/env node
// node cli 必须要有的特定文件头

// console.log("hello cli is working")
const fs = require("fs");
const inquirer = require("inquirer");
const path = require("path");
const ejs = require("ejs");

inquirer
  .prompt([
    /* Pass your questions in here */
    {
      type: "input",
      name: "title",
      message: "please input your title",
      default: "default",
    },
    // {
    //   type: "checkbox",
    //   name: "choice",
    //   choices: ["Choice A", new inquirer.Separator(), "choice B"],
    // },
  ])
  .then((answers) => {
    // Use user feedback for... whatever!!
    console.log("answers: ", answers);

    // 模板目录
    const tempDir = path.join(__dirname, "templates");
    console.log("tempDir: ", tempDir);

    // 目标目录
    const targetDir = process.cwd();
    console.log("targetDir: ", targetDir);

    fs.readdir(tempDir, (err, files) => {
      if (err) throw err;
      console.log("files: ", files);
      files.forEach((file) => {
        if (/\.html$/.test(file)) {
          // 利用模板引擎去渲染目标目录的文件
          ejs.renderFile(path.join(tempDir, file), answers, (err, result) => {
            if (err) throw err;
            fs.writeFileSync(path.join(targetDir, file), result);
          });
        } else {
          fs.readFile(path.join(tempDir, file), (err, result) => {
            if (err) throw err;
            fs.writeFileSync(path.join(targetDir, file), result);
          });
        }
      });
    });
  })
  .catch((error) => {
    if (error.isTtyError) {
      // Prompt couldn't be rendered in the current environment
    } else {
      // Something else went wrong
    }
  });
